//
//  MainViewController.swift
//  0623微博(swift)
//
//  Created by 岳挺 on 15/6/24.
//  Copyright © 2015年 yueting. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let tb = MainTabBar()
        tb.composeBtn.addTarget(self, action: "composeBtnDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        setValue(tb, forKey: "tabBar")
        addChildViewControllers()
    }
    
    //composeBtn点击方法
    func composeBtnDidClick(){
        let nav = UINavigationController(rootViewController: SendWeiboController())
        presentViewController(nav, animated: true, completion: nil)
        print("touch me")
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //print(tabBar.items as! NSArray)xcode7没有
    }
    
    func addChildViewControllers(){
        
        let data = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("MainVc.json", ofType: nil)!)
        
        //swift2.0新语法，错误抛出。可以强行try，但是不会捕获错误。
        do {
            let array = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
            
            for dict in array as! [[String: String]] {
                addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
            }
        }catch{
            print(error)
        }
    }
    
    func addChildViewController(vcName:String, title:String, imageName:String){
        
        tabBar.tintColor = UIColor.orangeColor()
        let str = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"]! as! String
        let vcStr = str + "." + vcName
        
        let cls : AnyClass = NSClassFromString(vcStr)!
        
        let vc = cls.new() as! UIViewController
        
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_heightlighted")
        
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }
}
